package file2;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Test1 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要遍历的目录：");
        String rootDirPath = scanner.next();
        System.out.println("请输入要查找的内容：");
        String content = scanner.next();
        File rootDir = new File(rootDirPath);
        if (!rootDir.isDirectory()) {
            System.out.println("输入的路径存在问题！");
            return;
        }
        List<File> result = new ArrayList<>();
        scanDirWithContent(rootDir, content, result);

        for (File f : result) {
            System.out.println(f.getCanonicalPath());
        }
    }

    private static void scanDirWithContent(File rootDir, String content, List<File> result) {
        File[] files = rootDir.listFiles();
        if (files == null) {
            return;
        }
        for (File f : files) {
            if (f.isFile()) {
                if (isContentExists(f, content)) {
                    result.add(f);
                }
            } else if (f.isDirectory()) {
                scanDirWithContent(f, content, result);
            }
        }
    }

    private static boolean isContentExists(File f, String content) {
        StringBuilder stringBuilder = new StringBuilder();
        try (Reader reader = new FileReader(f)) {
            int c;
            while (true) {
                c = reader.read();
                if (c == -1) {
                    break;
                }
                stringBuilder.append((char) c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.indexOf(content) != -1;
    }
}
